// pages/wristDetail/index.js
import * as echarts from '../../components/ec-canvas/echarts'

// 获取应用实例
const app = getApp()
const config = app.globalData;

var chart = null;
var ecgOption = {};// 心电图echart参数
function initChart(canvas, width, height, dpr) {
    chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // 像素
    });
    canvas.setChart(chart);
    return chart;
}
function getNumber(value){ 
    // 公倍数 
    let commonMultiple = 0.2; 
    // 取模 
    let modulus = value % commonMultiple; 
    if(modulus !== 0) { 
        // 模数不为0时 
        if(value < 0) { 
            // 判断正负 
            value += ((-commonMultiple) - modulus); 
        } else { 
            value += (commonMultiple - modulus); 
        } 
    } 
    return value <= 1.2 ? 1.2 : value; 
} 

Page({

    /**
     * 页面的初始数据
     */
    data: {
        imgurl:'',
        equipmentNo: '',
        showTip: false,

        // 是否在线
        isOnline: false,
        // 是否佩戴
        isWear: false,

        // 是否警报
        isAlarm: false,
        isMute: false,
        audioContext: null,

        // 是否故障
        isFault: false,

        timer: null,
        ecgDataTimer: null,
        wristData: {},

        showPopup: false,
        popupTitle: '',
        popupMsg: '',
        popupIcon: '',

        // echart对象初始化
        ec: {
            onInit: initChart
        },

        // 心电解析结果
        showECGRes: false,
        ecgResInfo: {},
        ecgInterval: {},
        firstReq: true,

        ecgTimer: null,// 心电图动态播放
        startVal: 0,// 心电图显示区域起点下标
        endVal: 250,// 心电图显示区域终点下标
        allSize: 0,// 心电图数据总长度
        isStopEcgPlay: false,//是否停止心电图播放
    },
    showTipBox() {
        this.setData({ showTip: true });
    },
    onClose() {
        this.setData({ showTip: false });
        if(this.data.isStopEcgPlay) {
            this.setData({ isStopEcgPlay: false }); 
            this.doECGInterval();
        }
    },
    // 查看历史
    handlerHis(){
        if(config.userInfo.phone == null){
            this.goLogin()
        } else {
            wx.navigateTo({
                url: '../../pages/wristhistory/index',
            })
        }
    },
    // 故障
    handlerError(){
      this.setData({
        showPopup: true,
        popupTitle: "设备故障",
        popupMsg: "请联系客服：12138",
        popupIcon: "../../size/image/phcall.png",
      });
    },
    goLogin(){
        wx.navigateTo({
            url: '../../pages/login/index',
        })
    },

    // 获取数据
    getData(){
        let that = this;
        that.requestData();
        that.setData({
            timer: setInterval(() => {
                that.requestData()
            }, 1 * 60 * 1000),
            ecgDataTimer: setInterval(() => {
                that.reqEcgData()
            }, 5 * 60 * 1000),
        });
    },

    // 请求数据
    requestData(){
        let equipmentNo = config.userInfo.equipmentNo;
        let equipmentType = config.userInfo.equipmentType;
        let that = this;
        wx.request({
            url: config.url+'api/equipment/getTj03RealtimeData?equipmentNo='+equipmentNo+'&phone='+app.globalData.userInfo.phone+'&equipmentType='+equipmentType,
            success(res){
                let data = res.data.data || {};

                // 设备是否在线和佩戴
                let eqFlag = data.equipmentStatus==0 && data.wstate==1;

                data.hr = data.hr&&eqFlag ? data.hr : 0;
                data.sbp = data.sbp&&eqFlag ? data.sbp : 0;
                data.dbp = data.dbp&&eqFlag ? data.dbp : 0;
                data.batpt = data.batpt&&eqFlag ? data.batpt : 0;
                that.setData({
                    wristData: data,
                });
                that.getStatus(data);

                // 首次进入页面请求心电数据，判断心电贴是否合法
                if(that.data.firstReq && data.ecgPatchPlginStatus !== 2 && eqFlag) {
                    that.reqEcgData();
                    that.setData({
                        firstReq: false,
                    });
                } else if(data.ecgPatchPlginStatus === 2){
                    that.showEcg([]);
                }
            }
        });
    },

    reqEcgData(){
        let equipmentNo = config.userInfo.equipmentNo;
        let equipmentType = config.userInfo.equipmentType;
        let that = this;
        wx.request({
            url: config.url+'api/equipment/getTj03RealtimeEcgData?equipmentNo='+equipmentNo+'&phone='+app.globalData.userInfo.phone+'&equipmentType='+equipmentType,
            success(res){
                let data = res.data.data || {};
                let arr = data.ecgData;

                // 电极片不合法不显示心电图
                if(that.data.wristData?.ecgPatchPlginStatus === 2) {
                    arr = [];
                }

                that.showEcg(arr);
                let ecgRes = data.ecgAnalysis;
                that.setData({
                    ecgResInfo: ecgRes?ecgRes:{},
                    ecgInterval: {
                        start: that.timestampToTime(arr[0].time),
                        end: that.timestampToTime(arr[arr.length - 1].time),
                    },
                });
            }
        });
    },

    showEcg(arr){
        let that = this;
        // 初始化数据
        let echartData = [];
        let xAxisData = [];
        for(var i = 0; i < arr.length; i ++){
            xAxisData.push(arr[i].time);
            echartData.push(arr[i].value / 1000);
        }

        that.setData({
            startVal: 0,
            endVal: 250,
            allSize: xAxisData.length
        });
        ecgOption = {
            xAxis: {
                type: 'category',
                boundaryGap: false,
                axisLine: { show: true, lineStyle: { color: '#F56C6C' } }, // 红色轴线
                axisLabel: { color: '#F56C6C', interval: 49 }, // 红色标签
                splitLine: { // 红色垂直网格线
                    show: true,
                    lineStyle: {
                        color: '#F56C6C',
                        type: 'dashed',
                        width: 1
                    },
                    interval: function (index) {
                        let size = xAxisData.length;
                        if (size <= 2) {
                            return true;
                        } else if (index % 10 == 0) {
                            return true;
                        }
                    }
                },
                data: xAxisData || [],
                axisLabel: {
                    interval: function (index) {
                        let size = xAxisData.length;
                        if (size <= 2) {
                            return true;
                        } else if (index % 125 == 0) {
                            return true;
                        }
                    },
                    formatter: function (value, index) {
                        return that.timestampToTime2(parseInt(value));
                    }
                }
            },
            yAxis: {
                type: 'value',
                splitNumber: 20,
                min: -1,
                max: 1,
                // min: function(value) { 
                //     value.min = getNumber(value.min); 
                //     value.max = getNumber(value.max); 
                //     return (Math.abs(value.min) > Math.abs(value.max)) ? value.min : -value.max; 
                // }, 
                // max: function(value) { 
                //     value.min = getNumber(value.min); 
                //     value.max = getNumber(value.max); 
                //     return (Math.abs(value.min) > Math.abs(value.max)) ? -value.min : value.max; 
                // },
                axisLine: { show: true, lineStyle: { color: '#F56C6C' } }, // 红色轴线
                axisLabel: { color: '#F56C6C', formatter: '{value}mv' }, // 红色标签
                splitLine: { // 红色水平网格线
                    show: true,
                    lineStyle: {
                        color: '#F56C6C',
                        type: 'dashed',
                        width: 1
                    }
                }
            },
            series: [{
                type: 'line',
                smooth: true,
                symbol: 'none',
                lineStyle: {
                    color: '#67C23A',
                    width: 1
                },
                areaStyle: {
                    color: 'rgba(103, 194, 58, 0.2)'
                },
                data: echartData || []
            }],
            grid: {
                backgroundColor: '#000000', // 医疗设备常见的黑色背景
                borderWidth: 0,
                top: 10,
                bottom: 60,
                left: 45,
                right: 30
            },
            dataZoom: [
                {
                    type: 'inside',
                    startValue: that.data.startVal,
                    endValue: that.data.endVal
                },
                {
                    startValue: that.data.startVal,
                    endValue: that.data.endVal,
                    rangeMode: ['value', 'value'],
                    zoomLock: true,
                    brushSelect: false,
                }
            ],
            animation: false,
        }

        // 初始化渲染
        chart.setOption(ecgOption);
        // 监听dataZoom的坐标，用于恢复滚动
        chart.on('dataZoom', function (event) {
            if(event.type === 'datazoom') {
                let start = event.start;
                let end = event.end;

                if(!start) {
                    if (event.batch && event.batch[0]?.type === 'datazoom') {
                        start = event.batch[0].start;
                    }
                }
                if(!end) {
                    if (event.batch && event.batch[0]?.type === 'datazoom') {
                        end = event.batch[0].end;
                    }
                }

                that.setData({
                    startVal: Math.ceil(that.data.allSize * start / 100),
                    endVal: Math.ceil(that.data.allSize * end / 100)
                });
            }
        });
        that.doECGInterval();
    },
    doECGInterval(){
        clearInterval(this.data.ecgTimer);
        this.setData({
            ecgTimer: setInterval(() => {
                let s = this.data.startVal + 50;
                let e = this.data.endVal + 50;
                if(e >= this.data.allSize) {
                    s = 0;
                    e = 250;
                }
                this.setData({
                    startVal: s,
                    endVal: e
                });
                ecgOption.dataZoom = [
                    {
                        type: 'inside',
                        startValue: this.data.startVal,
                        endValue: this.data.endVal
                    },
                    {
                        startValue: this.data.startVal,
                        endValue: this.data.endVal,
                        rangeMode: ['value', 'value'],
                        zoomLock: true,
                        brushSelect: false,
                    }
                ],
                chart.setOption(ecgOption);
            }, 200)
        });
    },
    stopPlay(){
        this.setData({
            isStopEcgPlay: ! this.data.isStopEcgPlay
        });
        if(this.data.isStopEcgPlay) {
            clearInterval(this.data.ecgTimer);
        } else {
            this.doECGInterval();
        }
    },

    openECGRes(){
        this.setData({ showECGRes: true });
    },
    closeECGRes(){
        this.setData({ showECGRes: false });
        if(this.data.isStopEcgPlay) {
            this.setData({ isStopEcgPlay: false }); 
            this.doECGInterval();
        }
    },

    getStatus(data){
        let that = this;
        // 是否佩戴(穿戴状态:0-未佩戴手环;1-已佩戴手环)
        let wearStatus = data.wstate == 1;
        // 是否故障（0-有故障，1-无故障）
        let faultState = data.restHeart == 0;
        // 是否在线(设备状态 null=未使用；0=在线；1=离线；)
        let onlineStatus = data.equipmentStatus == 0;        

        that.setData({
            isWear: wearStatus,
            isOnline: onlineStatus,
            isFault: faultState,
            isAlarm: false,
        });
        that.data.audioContext.pause();

        /**
         * 判断报警
         * 在线及佩戴状态下
         * 脉率：中间值80、下限50、上限110
         * 收缩压sbp：90~119mmHg
         * 舒张压dbp：60~79mmHg
         */
        if(wearStatus && onlineStatus
          && (data.hr < 50 || data.hr > 110
          || data.sbp < 90 || data.sbp > 119
          || data.dbp < 60 || data.dbp > 79)
        ) {
            // 警报状态
            that.setData({
                isAlarm: true
            });

            // 判断是否静音
            if(! that.data.isMute && that.data.isOnline && that.data.isWear) {
                // 不是静音状态下，播放铃声
                that.data.audioContext.play();
            } else {
                that.data.audioContext.pause();
            }
        } else {
            // 警报状态
            that.setData({
                isAlarm: false
            });
            that.data.audioContext.pause();
        }

    },
    closeRing(){
        let that = this;
        // 开启静音
        app.globalData.isMute = true;
        that.setData({
            isMute: true,
        });
        // 停止播放铃声
        that.data.audioContext.pause();
    },
    openRing(){
      let that = this;
      // 关闭静音
      app.globalData.isMute = false;
      that.setData({
        isMute: false
      });
      // 如果警报状态，直接响铃
      if(that.data.isAlarm && that.data.isOnline && that.data.isWear){
        that.data.audioContext.play();
      }
    },
    /**
     * 时间戳转时间字符串
     */
    timestampToTime(timestamp) {
        var date = new Date(timestamp);
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        var mills = date.getMilliseconds();
        return year + "-" + (month<10?"0"+month:month) + "-" + (day<10?"0"+day:day) + " " + (hours<10?"0"+hours:hours) + ":" + (minutes<10?"0"+minutes:minutes) + ":" + (seconds<10?"0"+seconds:seconds) + "." + mills;
    },
    timestampToTime2(timestamp) {
        var date = new Date(timestamp);
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        var mills = date.getMilliseconds();
        return (hours<10?"0"+hours:hours) + ":" + (minutes<10?"0"+minutes:minutes) + ":" + (seconds<10?"0"+seconds:seconds) + "." + mills;
    },
    initPage(){
        let that = this;
        that.data.audioContext.pause();
        clearInterval(that.data.timer);
        clearInterval(that.data.ecgDataTimer);
        clearInterval(that.data.ecgTimer);
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        
        this.setData({
            imgurl: config.imgurl,
            equipmentNo: config.userInfo.equipmentNo,
            isMute: config.isMute,
        })

        let audioContext = wx.createInnerAudioContext();
        audioContext.src = config.audiourl;
        audioContext.loop = true;
        this.setData({
            audioContext: audioContext
        });

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.initPage();
        this.getData();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        this.initPage();
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        this.initPage();
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})